package com.flyco.modules.stm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.flyco.common.constant.FillRuleConstant;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.FileUtil;
import com.flyco.common.util.FillRuleUtil;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.entity.OmsOrderPriceDistance;
import com.flyco.modules.oms.service.IOmsOrderPriceDistanceService;
import com.flyco.modules.pms.entity.PmsSkuStock;
import com.flyco.modules.pms.mapper.PmsSkuStockMapper;
import com.flyco.modules.stm.entity.StmChannelInfo;
import com.flyco.modules.stm.entity.StmChannelProductApply;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.mapper.StmStoreInfoMapper;
import com.flyco.modules.stm.service.IStmChannelInfoService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.system.entity.SysDepart;
import com.flyco.modules.system.entity.SysMail;
import com.flyco.modules.system.entity.SysUser;
import com.flyco.modules.system.mapper.SysDepartMapper;
import com.flyco.modules.system.model.SysDepartStoreModel;
import com.flyco.modules.system.service.ISysMailService;
import com.flyco.modules.system.service.ISysUserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 门店
 * @Author: flyco
 * @Date: 2020-09-18
 * @Version: V1.0
 */
@Slf4j
@Service
public class StmStoreInfoServiceImpl extends ServiceImpl<StmStoreInfoMapper, StmStoreInfo> implements IStmStoreInfoService {

    @Autowired
    private StmStoreInfoMapper stmStoreInfoMapper;
    @Autowired
    private SysDepartMapper sysDepartMapper;
    @Autowired
    private PmsSkuStockMapper pmsSkuStockMapper;
    @Value(value = "${spring.mailTemp.path}")
    private String path;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysMailService mailService;
    @Autowired
    private IOmsOrderPriceDistanceService distanceService;
    @Autowired
    private IStmChannelInfoService channelInfoService;

    @Override
    public void generateSku(Long partnerId, Long storeId) {
        stmStoreInfoMapper.generateSku(partnerId, storeId);
    }

    @Override
    public void generateStoreStock(Long partnerId, Long storeId) {
        stmStoreInfoMapper.generateStoreStock(partnerId, storeId);
    }

    @Override
    public Long getNextStoreId() {
        return stmStoreInfoMapper.getNextStoreId();
    }

    @Transactional
    @Override
    public void saveDepartStoreData(SysDepartStoreModel departStoreModel) {
        if (oConvertUtils.isNotEmpty(departStoreModel)) {
            if (departStoreModel.getParentId() == null) {
                departStoreModel.setParentId("");
            }
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            Long storeId = stmStoreInfoMapper.getNextStoreId();
            if (oConvertUtils.isEmpty(storeId)) {
                storeId = 1L;
            }
            departStoreModel.setStoreId(storeId);
            departStoreModel.setId("" + sysUser.getPartnerId() + "-" + departStoreModel.getStoreId());
            JSONObject formData = new JSONObject();
            formData.put("parentId", departStoreModel.getParentId());
            String[] codeArray = (String[]) FillRuleUtil.executeRule(FillRuleConstant.DEPART, formData);
            departStoreModel.setOrgCode(codeArray[0]);
            departStoreModel.setOrgType(codeArray[1]);
            departStoreModel.setDelFlag("0");
            departStoreModel.setDepartOrder(departStoreModel.getStoreId().intValue());
            StmStoreInfo storeInfo = BeanUtils.instantiateClass(StmStoreInfo.class);
            BeanUtils.copyProperties(departStoreModel, storeInfo);
            stmStoreInfoMapper.insert(storeInfo);
            SysDepart depart = BeanUtils.instantiateClass(SysDepart.class);
            BeanUtils.copyProperties(departStoreModel, depart);
            sysDepartMapper.insert(depart);
        }
    }

    public Boolean editDepartStoreDataById(SysDepartStoreModel departStoreModel) {
        if (oConvertUtils.isNotEmpty(departStoreModel)) {
            StmStoreInfo storeInfo = BeanUtils.instantiateClass(StmStoreInfo.class);
            BeanUtils.copyProperties(departStoreModel, storeInfo);
            Integer s = stmStoreInfoMapper.updateById(storeInfo);
            log.info("s:" + s);
            SysDepart depart = BeanUtils.instantiateClass(SysDepart.class);
            BeanUtils.copyProperties(departStoreModel, depart);
            Integer d = sysDepartMapper.updateById(depart);
            log.info("d:" + d);
            if (s >= 1 && d >= 1) {
                log.info("aaaaaa:");
                return true;
            }
        }
        return false;
    }

    @Override
    public List<StmStoreInfo> getStoreInfoList(List<Long> storeIds) {
        return list(Wrappers.lambdaQuery(StmStoreInfo.class).in(StmStoreInfo::getStoreId, storeIds));
    }

    @Override
    public List<PmsSkuStock> getStockProductCount() {
        return pmsSkuStockMapper.getStockProductCount();
    }

    @Override
    public StmStoreInfo getByStoreId(Long storeId) {
        LambdaQueryWrapper<StmStoreInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StmStoreInfo::getId, storeId);
        StmStoreInfo store = getOne(queryWrapper);
        if (store != null) {
            return store;
        }
        //by martin 做兼容逻辑,现根据id找不到在按照以前的逻辑查询
        LambdaQueryWrapper<StmStoreInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(StmStoreInfo::getStoreId, storeId);
        List<StmStoreInfo> storeList = stmStoreInfoMapper.selectList(queryWrapper1);
        if (!CollectionUtils.isEmpty(storeList)) {
            return storeList.get(0);
        }
        return new StmStoreInfo();
    }

    @Override
    public List<StmStoreInfo> getStoreAndChannel() {
        return stmStoreInfoMapper.getStoreAndChannel();
    }

    @Override
    public void sendMailForApprove(StmStoreInfo storeInfo) {

        String content = storeInfo.getName();

        String subject = "江心味业订货平台经销商审核通知";
        String realPath = path + "/storeApplyApproveMailContent.html";

        //给销售发审核不通过通知
        SysUser userInfo = userService.getById(storeInfo.getSaleUserId());

        if (userInfo == null) {
            log.info("sendMailForApprove,未找到对应销售。storeInfo.getSaleUserId()=" + storeInfo.getSaleUserId());
            return;
        }
        String mails = userInfo.getEmail();
        if (StringUtils.isEmpty(mails)) {
            log.info("sendMailForApprove,销售未配置邮件。userInfo.getEmail()=" + userInfo.getEmail());
            return;
        }
        SysMail mail = new SysMail();
        String tempContent = FileUtil.readFile(realPath);
        tempContent = tempContent.replaceAll("%s", content);
        mail.setContent(tempContent);
        mail.setReceive(mails);
        mail.setBusinessType("storeApplyApprove");
        mail.setSubject(subject);
        mail.setSourceId(storeInfo.getId());
        mailService.sendMail(mail);

    }

    @Override
    public List<StmStoreInfo> queryStoreListAndOrderDistance() {

        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(StmStoreInfo::getStatus, 0);
        List<StmStoreInfo> storeInfoList = list(wrapper);

        //获取渠道，在经销商后面显示
        Map<String, StmChannelInfo> channelInfoMap = channelInfoService.list()
                .stream()
                .collect(Collectors.toMap(StmChannelInfo::getChannelId, key1 -> key1));

        storeInfoList.forEach(o -> {
            StmChannelInfo channelInfo = channelInfoMap.get(o.getChannelId());
            if (channelInfo != null) {
                o.setName(o.getName() + "-" + channelInfo.getName());
            }
        });

        List<OmsOrderPriceDistance> distanceList = distanceService.list()
                .stream().filter(o -> o.getStoreId() != null).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(distanceList)) {
            Map<String, List<OmsOrderPriceDistance>> distanceMap = distanceList
                    .stream()
                    .collect(Collectors.groupingBy(OmsOrderPriceDistance::getStoreId));

            storeInfoList.forEach(o -> {
                List<OmsOrderPriceDistance> distances = distanceMap.get(o.getId());
                if (!CollectionUtils.isEmpty(distances)) {
                    o.setName(o.getName() + "(已配置)");
                }
            });
        }
        return storeInfoList;
    }


    @Override
    public List<StmStoreInfo> getStoreList() {

        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StmStoreInfo::getStatus, 9);
        return stmStoreInfoMapper.selectList(wrapper);
    }

    @Override
    public List<StmStoreInfo> getStoreListByPartnerId(Long partnerId) {
        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StmStoreInfo::getStatus, 9).eq(StmStoreInfo::getPartnerId, partnerId);
        return stmStoreInfoMapper.selectList(wrapper);
    }

    @Override
    public List<StmStoreInfo> getCompanyList() {

        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StmStoreInfo::getStatus, 9);
        return stmStoreInfoMapper.selectList(wrapper).stream().map(O -> {
            StmStoreInfo storeInfo = new StmStoreInfo();
            storeInfo.setCompanyCode(O.getCompanyCode());
            return storeInfo;
        }).distinct().collect(Collectors.toList());
    }

    @Override
    public List<StmStoreInfo> getStoreListByName(String storeName, Long partnerId) {
        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StmStoreInfo::getStatus, 9);
        if (!StringUtils.isEmpty(storeName)) {
            wrapper.like(StmStoreInfo::getName, storeName);
        }
        wrapper.eq(StmStoreInfo::getPartnerId, partnerId);
        return stmStoreInfoMapper.selectList(wrapper);
    }

    @Override
    public List<StmStoreInfo> getStoreInfoDisabledList() {
        LambdaQueryWrapper<StmStoreInfo> wrapper = new LambdaQueryWrapper();
        wrapper.eq(StmStoreInfo::getStatus, 9)
                .eq(StmStoreInfo::getDisabledStatus, 0)
                .isNotNull(StmStoreInfo::getDisabledTime);
        return stmStoreInfoMapper.selectList(wrapper);
    }
}
